angular.module('starter.creditController', [])


//信用管理
.controller('CreditCtrl', function($scope,$state,$window,CreditService,$ionicPopup) {
	var userId=null;
	try{
		userId=JSON.parse($window.localStorage["user"] || '{}').userId;
	}catch(e){
		
	}
	
	var token=null;
	try{
		token=JSON.parse($window.localStorage["user"] || '{}').token;
	}catch(e){
		
	}
	
	$scope.$on('$ionicView.beforeEnter', function(event, data) {
		if(userId==null||token==null){
			$state.go('login');
			return ;
		}
	});
	
	//显示认证信息
	$scope.showAuth=function(level){
		var template='';
		if(level==1){
			template='信用身价达到3000，且完成2个高级认证';
		}else if(level==2){
			template='信用身价达到6000，且完成3个高级认证';
		}else if(level==3){
			template='信用身价达到10000，且完成4个高级认证，平台将适时邀请升级，请保持良好信用记录。';
		}
		
		$ionicPopup.show({
	 		 title: '升级条件',
		     template:template,
		   	 scope: $scope,
		   	 cssClass: 'tipCss',
		   	 buttons: [
		   	 	{ 
			   	 	text: '取消',
				},
			   	{ 
			   	 	text: '<b>去认证</b>',
			   	 	type: 'button-positive',
					onTap:function(e){
					  	$state.go('tab.authenTication');
					}
				}
			]
		});
	}
	
	var loadEchar=function(data){
		//获取页面图表
		var myChart = echarts.init(document.getElementById('creditMap'));
	    // 指定图表的配置项和数据
	    var option = {
		    series : [
		        {
		            min:data.tlevel.levelAccount,
		            max:data.tlevel.account,
		            startAngle:'180',
		            radius:'100%',
		            endAngle:'0',
		            type:'gauge',
		            center:	['50%', '50%'],
		            splitNumber:2,
		            detail:{
					    show : true,
					    backgroundColor: 'rgba(0,0,0,0)',
					    borderWidth: 0,
					    borderColor: '#',
					    width: 100,
					    height: 100,
					    offsetCenter: [0, '10%'],
					    formatter: null,
					    textStyle: {
					        color: 'auto',
					        fontSize : 14
					    }
					},      
		            data:[{value: data.creditValue,name: '当前信用身价'}],
		            axisLine:{
		            	show:true,
		            	lineStyle: {
		                    color: [[0.2, '#a2f9b0'],[0.4, '#7eec90'],[0.6, '#56dd6c'],[1, '#42bd55']], 
		                    width: 4
		                }
		            },
		            axisTick:{
		            	show:true
		            },
		            axisLabel:{
		            	show:true,
		            	textStyle: {       // 其余属性默认使用全局文本样式，详见TEXTSTYLE
		                    color: 'auto',
		                    fontSize:14
		                }
		            },
		            splitLine:{
		            	show:true
		            },
		            pointer : {
			            width : 1
			        }
		        }
		    ]
		};
	
	    // 使用刚指定的配置项和数据显示图表。
	    myChart.setOption(option);
	}
	
	//查询信用等级信息v
	$scope.data={};
	CreditService.getCreditLevel().then(function(response) {
		if(response.success=="success"){
			$scope.updateLevel=parseInt(response.data.creditLevel)+1;
			$scope.data=response.data;
			console.log($scope.data);
			
			//加载图表
			loadEchar($scope.data);
		}
	});
	
	$scope.customerId=userId;
	$scope.creditHelps=function(){
		
		$state.go('tab.creditHelp');
	}
	
	
})

//必填类
.controller('GeneralInfoCtrl', function($scope,$timeout,CommonService,$cordovaCamera,$ionicPopup,$cordovaImagePicker,$ionicModal,CreditService,$location,$ionicLoading,$cordovaContacts,MyService) {

    $scope.bigPic=function(str){
      if(str==1){
      	$scope.TitileName="身份证正面高清照";
	  	$scope.urlPic="img/credit/sfz-fm1.png";
      }
       if(str==2){
      	$scope.TitileName="身份证高清自拍照";
	  	$scope.urlPic="img/credit/sc-fm1.png";
      }
       if(str==3){
      	$scope.TitileName="微信“账户与安全”高清图片";
	  	$scope.urlPic="img/credit/wx-fm2.png";
      }
       if(str==4){
      	$scope.TitileName="个人生活照";
	  	$scope.urlPic="img/credit/shz-fm1.png";
      }
       $ionicModal.fromTemplateUrl('templates/modal.html', {
	    scope: $scope
	  }).then(function(modal) {
	    $scope.modal = modal;
	    $scope.modal.show(); 
	  }); 
     
   } 
   
  	
	
	//必填类对象
	var generalInfo=new Object();
	$scope.generalInfo=generalInfo;
	
	//个人生活照
	var lifePicAddressList=new Array();
	$scope.lifePicAddressList=lifePicAddressList;
	
	//上传图片 1身份证正面 2手持身份证正面 3个人生活照
	
$scope.uploadPic=function(type){
		//调用摄像头
		if(type==1||type==2){
			//拍照
	        var options = {
		        quality: 100,
		        destinationType: Camera.DestinationType.FILE_URI,
		        sourceType: Camera.PictureSourceType.CAMERA,
		        allowEdit: false,
		        encodingType:Camera.EncodingType.JPEG,
		        mediaType:0,
		        cameraDirection:0,
		        popoverOptions: CameraPopoverOptions,
		        saveToPhotoAlbum: false
			}; 
	  
  			$cordovaCamera.getPicture(options).then(function(imageURI) {
            	$ionicLoading.show({
	      			template: '上传中，请稍后...'
	    		});
            	//拍照成功后执行上传
	          	CommonService.uploadPic(imageURI).then(function(response) {
	          		//上传成功
	          		if(response.success=='success'){
	          			if(type==1){
	          				//处理身份证正面
	          				generalInfo.certificateNoZAddress=response.message;
	          			}else if(type==2){
	          				//处理手持身份证
	          				generalInfo.certificateNoAddress=response.message;
	          			}
	          		}
	          		
	          		$ionicLoading.hide();
			   	},function(e){
			   		$ionicLoading.hide();
			   	});
	        });
            
	    }else if(type==3){
	    	var certificateNoZAddress=$scope.generalInfo.certificateNoZAddress;
	    	if(certificateNoZAddress==null||certificateNoZAddress==''){
	    		$ionicPopup.alert({title:'系统提示',template:'请先添加身份证正面'});
	    		return ;
	    	}
	    	
			//调用手机相册
	        var options = {  
	            maximumImagesCount: 1,
	            quality: 100
	        };
	        
        	$cordovaImagePicker.getPictures(options).then(function (results) { 
        		if(results!=null&&results[0]!='O'&&results.length>0){
	        		$ionicLoading.show({
		      			template: '上传中，请稍后...'
		    		});
		    		
	    			//拍照成功后执行上传
		          	CommonService.uploadPic(results[0]).then(function(response) {
		          		if(response.success=='success'){
			          		//处理手持身份证
			          		generalInfo.weiXinAddress=response.message;
		          		}else{
		          			$ionicPopup.alert({title:'系统提示',template:response.message});
		          		}
		          		
		          		$ionicLoading.hide();
				   	});
				}
	        },function(e){
	        	$ionicLoading.hide();
	        });
	    	
	    }else if(type==4){
	    	var certificateNoZAddress=$scope.generalInfo.certificateNoZAddress;
	    	if(certificateNoZAddress==null||certificateNoZAddress==''){
	    		$ionicPopup.alert({title:'系统提示',template:'请先添加身份证正面'});
	    		return ;
	    	}
	    	
			//调用手机相册
	        var options = {  
	            maximumImagesCount: 10,
	            quality:100
	        };
			$cordovaImagePicker.getPictures(options).then(function (results) { 
        		if(results!=null&&results[0]!='O'&&results.length>0){
	        		$ionicLoading.show({
		      			template: '上传中，请稍后...'
		    		});
		    		for(var i=0;i<results.length;i++){
		    			var j=results.length-1;
		    			CommonService.uploadPic(results[i]).then(function(response) {
			          		if(response.success=='success'){
				          		//处理手持身份证
				          		var object=new Object();
				          		object.lifePicAddress=response.message;
				          		lifePicAddressList.push(object);
			          		}else{
			          			$ionicPopup.alert({title:'系统提示',template:response.message});
			          		}
//			          		$timeout(function(){ 
//			          			$ionicLoading.hide();
//			          		},4000);
			          		$ionicLoading.hide();
					   	});
		    		}
		    	}
	        },function(e){
	        	$ionicLoading.hide();
	        });
	    }
	}
	
	//默认联系人数量
	generalInfo.contact=25;
	
	//获取联系人数量
//	var options = {};
//	options.filter = "";
//	options.multiple = true;
//	try{
//		$cordovaContacts.find(options).then(function(result) {
//	      generalInfo.contact=result.length;
//	  	});
//	}catch(e){
//
//	}
	

	//保存必填类数据
	$scope.saveGeneralInfo=function(){
		//将集合添加到对象
		generalInfo.lifePicAddressList=lifePicAddressList;
		
		//qq验证
		if(generalInfo.qq==null||generalInfo.qq==''){
			$ionicPopup.alert({title:'系统提示',template:'QQ号码不能为空'});
			return ;
		}
		
		//微信验证
		if(generalInfo.weixin==null||generalInfo.weixin==''){
			$ionicPopup.alert({title:'系统提示',template:'微信不能为空'});
			return ;
		}
		
		//验证必填类生活照图片数量
		if(generalInfo.certificateNoZAddress==null||generalInfo.certificateNoZAddress==''){
			$ionicPopup.alert({title:'系统提示',template:'身份证正面不能为空'});
			return ;
		}
		
		//高清自拍照不能为空
		if(generalInfo.certificateNoAddress==null||generalInfo.certificateNoAddress==''){
			$ionicPopup.alert({title:'系统提示',template:'身份证高清自拍照不能为空'});
			return ;
		}
		
		//微信个人信息图片不能为空
		if(generalInfo.weiXinAddress==null||generalInfo.weiXinAddress==''){
			$ionicPopup.alert({title:'系统提示',template:'身份证个人信息高清图片不能为空'});
			return ;
		}

		//个人生活照数量不能小于3三张
		if(generalInfo.lifePicAddressList==null){
			$ionicPopup.alert({title:'系统提示',template:'个人生活照数量不能小于3张'});
			return ;
		}

		//个人生活照数量不能小于3三张
		if(generalInfo.lifePicAddressList.length<3){
			$ionicPopup.alert({title:'系统提示',template:'个人生活照数量不能小于3张'});
			return ;
		}
			$ionicLoading.show({
  			      template: '保存中...'
		        });
		  //alert(JSON.stringify(generalInfo));     
		//执行保存
		CreditService.saveGeneralInfo(generalInfo).then(function(response) {
			if(response.success=="success"){
					$ionicLoading.hide();
				$ionicPopup.alert({title:'系统提示',template:response.message}).then(function(res){
					//根据历史记录判断应该跳到什么地方，因为该方法在两个地方用到
					var path=$location.$$path;
					if(path.contains('authBandCard')){
						//跳转到发标界面
						$state.go('tab.addProduce');
					}else{
						$state.go('tab.credit');
					}
					
				});
			}else{
				$ionicLoading.hide();
				$ionicPopup.alert({title:'系统提示',template:response.message});
			}
        });
	}
})

//高级认证
.controller('AuthenTicationCtrl', function($scope,CreditService,$window,$ionicLoading,$ionicPopup,$sce,$ionicModal,$state) {

	//构建集合
	var zlMap=[
		{name:'芝麻认证',pic:'icon_zmxy.png',status:0,key:'saveJuHeZmxy',score:null,money:null},
		{name:'社保查询',pic:'icon_sbcx.png',status:0,key:'saveJuHeSecurity',score:null,money:null},
		{name:'运营商认证',pic:'icon_yys.png',status:0,key:'saveJuHeMno',score:null,money:null},
		{name:'央行征信报告',pic:'icon_yn.png',status:0,key:'saveJuHeBankCredit',score:null,money:null},
		{name:'行车证',pic:'icon_xcz.png',status:0,key:'saveJuHeCar',score:null,money:null},
		{name:'公积金查询',pic:'icon_gjj.png',status:0,key:'saveJuHeFund',score:null,money:null},
		{name:'京东消费',pic:'icon_jdxf.png',status:0,key:'saveJuHeJingDong',score:null,money:null},
		{name:'淘宝消费',pic:'icon_tbxf.png',status:0,key:'saveJuHeTaoBao',score:null,money:null},
		{name:'户籍地址查询',pic:'icon_hicx.png',status:0,key:'saveJuHeRegister',score:null,money:null},
		{name:'乘机人统计',pic:'icon_cjrtj.png',status:0,key:'saveJuHeFly',score:null,money:null},
		{name:'银行卡消费报告',pic:'icon_yhkxf.png',status:0,key:'saveJuHeBankCard',score:null,money:null},
		{name:'婚姻状况',pic:'icon_hycx.png',status:0,key:'saveJuHeMarrage',score:null,money:null},
		{name:'驾驶证认证',pic:'icon_jsz.png',status:0,key:'saveJuHeDrive',score:null,money:null},
		{name:'职业资格证书',pic:'icon_zyzg.png',status:0,key:'saveJuHeProfession',score:null,money:null},
		{name:'学历和学籍认证',pic:'icon_xlxj.png',status:0,key:'saveJuHeDegree',score:null,money:null}
	];
	
	$scope.zlMap=zlMap;
	
	$scope.$on('$ionicView.beforeEnter', function(event, data) {
		var customerId=JSON.parse($window.localStorage["user"] || '{}').userId;
		//查询高级认证信息
		CreditService.getJuHeStatus(customerId).then(function(response) {
			if(response.success=="success"){
				var data = response.data;
				if(data!=null){
					for(var i=0;i<data.length;i++){
						for(var j=0;j<zlMap.length;j++){
							if(zlMap[j].key==data[i].func){
								zlMap[j].status=data[i].status;
								zlMap[j].score=data[i].score;
								zlMap[j].money=data[i].money;
								//处理运营商
								if(zlMap[j].key=='saveJuHeMno'){
									zlMap[j].mnoTime=data[i].mnoTime;
								}
							}
						}
					}
				}
				$scope.zlMap=zlMap;
			}
		},function(e){
		});
	});
	
	//高级认证处理
	$scope.saveAuth=function(data){
		if(data.name=='运营商认证'){
		 $state.go('tab.mno');
		 return 0;		 
		}
/*		if(data.name=="芝麻认证"){
		 return 0;		 
		 }*/
		//定义数据模型
		$scope.authData={};
		
		var userId=null;
        var token=null;
        try{
        	userId=JSON.parse($window.localStorage["user"] || '{}').userId;
        	token=JSON.parse($window.localStorage["user"] || '{}').token;
        }catch(e){
        	
        }
		
		//定义高级认证公共信息界面
		var authHtml=
		'<div style="padding:10px;">'+
			'<div style="height:30px;">即将进行'+data.name+'</div>'+
			'<div style="font-size:13px;color:#808080;height:30px;">温馨提示</div>'+
			'<div style="font-size:13px;color:#808080;height:30px;">第三方平台收取'+data.money+'元/次</div>'+
		'</div>'+
		'<div class="list">';
/*		//银行卡消费报告
		if(data.key=='saveJuHeBankCard'){
			authHtml+=
			'<label class="item item-input">'+
			    '<span class="input-label" style="padding-left:0px;">银行卡号</span>'+
			    '<input type="text" ng-model="authData.bankCardNo" placeholder="银行卡号">'+
			'</label>';
		}*/
		//央行征信认证
		if(data.key=='saveJuHeBankCredit'){
			authHtml+=
			'<label class="item item-input">'+
			    '<span class="input-label" style="padding-left:0px;">征信账号</span>'+
			    '<input type="text" ng-model="authData.username" placeholder="请输入央行征信账号">'+
			'</label>'+
			'<label class="item item-input">'+
			    '<span class="input-label" style="padding-left:0px;">征信密码</span>'+
			    '<input type="password" ng-model="authData.password" placeholder="请输入央行征信密码">'+
			'</label>'+
			'<label class="item item-input">'+
			    '<span class="input-label" style="padding-left:0px;">征信验证码</span>'+
			    '<input type="text" ng-model="authData.middleAuthCode" placeholder="请输入央行征信身份验证码">'+
			'</label>';
		}
		
		//公积金
		if(data.key=='saveJuHeFund'){
			authHtml+=
			'<label class="item item-input">'+
			    '<span class="input-label" style="padding-left:0px;">公积金帐号</span>'+
			    '<input type="text" ng-model="authData.username" placeholder="请输入公积金帐号">'+
			'</label>'+
			'<label class="item item-input">'+
			    '<span class="input-label" style="padding-left:0px;">公积金密码</span>'+
			    '<input type="password" ng-model="authData.password" placeholder="请输入公积金密码">'+
			'</label>'+
			'<label class="item item-input">'+
			    '<span class="input-label" style="padding-left:0px;">公积金地址</span>'+
			    '<input type="text" ng-model="authData.area" placeholder="请输入公积金地址">'+
			'</label>';
		}
		
		//京东
		if(data.key=='saveJuHeJingDong'){
			authHtml+=
			'<label class="item item-input">'+
			    '<span class="input-label" style="padding-left:0px;">京东帐号</span>'+
			    '<input type="text" ng-model="authData.loginName" placeholder="请输入京东帐号">'+
			'</label>'+
			'<label class="item item-input">'+
			    '<span class="input-label" style="padding-left:0px;">京东密码</span>'+
			    '<input type="password" ng-model="authData.passwd" placeholder="请输入京东密码">'+
			'</label>';
		}
		
		//淘宝
		if(data.key=='saveJuHeTaoBao'){
			authHtml+=
			'<label class="item item-input">'+
			    '<span class="input-label" style="padding-left:0px;">淘宝帐号</span>'+
			    '<input type="text" ng-model="authData.loginName" placeholder="请输入淘宝帐号">'+
			'</label>'+
			'<label class="item item-input">'+
			    '<span class="input-label" style="padding-left:0px;">淘宝密码</span>'+
			    '<input type="password" ng-model="authData.password" placeholder="请输入淘宝密码">'+
			'</label>';
		}
		
		//社保 
		if(data.key=='saveJuHeSecurity'){
			authHtml+=
			'<label class="item item-input">'+
			    '<span class="input-label" style="padding-left:0px;">社保帐号</span>'+
			    '<input type="text" ng-model="authData.username" placeholder="请输入社保帐号">'+
			'</label>'+
			'<label class="item item-input">'+
			    '<span class="input-label" style="padding-left:0px;">社保密码</span>'+
			    '<input type="password" ng-model="authData.password" placeholder="请输入社保密码">'+
			'</label>'+
			'<label class="item item-input">'+
			    '<span class="input-label" style="padding-left:0px;">社保地址</span>'+
			    '<input type="text" ng-model="authData.area" placeholder="请输入社保地址">'+
			'</label>';
		}
		
		authHtml+=
			'<label class="item item-input">'+
			    '<span class="input-label" style="padding-left:0px;">交易密码</span>'+
			    '<input type="password" ng-model="authData.dealCode" placeholder="请输入您的交易密码">'+
			'</label>'+
		'</div>';
		
		var myPopup = $ionicPopup.show({
			template: authHtml,
			title: '系统提示',
			cssClass:'my-custom-popup',
			scope: $scope,
			buttons: [
				{ text: '取消' },
				{ 
					text: '<b>确定</b>',
					type: 'button-positive',
					onTap: function(e) {
			           if (!$scope.authData.dealCode) {
			             	e.preventDefault();
			            }else{
			             	doAuth(data.key,$scope.authData);
			            }
			        }
				}
			]
		});
			
		//认证完成后返回程序
		$scope.cancelCredit=function(){		
			//关闭
			$scope.modal.hide();
			//重新加载数据
			var customerId=JSON.parse($window.localStorage["user"] || '{}').userId;
			//查询高级认证信息
			CreditService.getJuHeStatus(customerId).then(function(response) {
				if(response.success=="success"){
					var data = response.data;
					if(data!=null){
						for(var i=0;i<data.length;i++){
							for(var j=0;j<zlMap.length;j++){
								if(zlMap[j].key==data[i].func){
									zlMap[j].status=data[i].status;
									zlMap[j].score=data[i].score;
									zlMap[j].money=data[i].money;
									//处理运营商
									if(zlMap[j].key=='saveJuHeMno'){
										zlMap[j].mnoTime=data[i].mnoTime;
									}
								}
							}
						}
					}
					$scope.zlMap=zlMap;
				}
			},function(e){
				
			});
		}
		
		//认证完成重新加载
		$scope.cancelCreditOk=function(){		
			//重新加载数据
			var customerId=JSON.parse($window.localStorage["user"] || '{}').userId;
			//查询高级认证信息
			CreditService.getJuHeStatus(customerId).then(function(response) {
				if(response.success=="success"){
					var data = response.data;
					if(data!=null){
						for(var i=0;i<data.length;i++){
							for(var j=0;j<zlMap.length;j++){
								if(zlMap[j].key==data[i].func){
									zlMap[j].status=data[i].status;
									zlMap[j].score=data[i].score;
									zlMap[j].money=data[i].money;
									//处理运营商
									if(zlMap[j].key=='saveJuHeMno'){
										zlMap[j].mnoTime=data[i].mnoTime;
									}
								}
							}
						}
					}
					$scope.zlMap=zlMap;
				}
			},function(e){
				
			});
		}		
		
		//处理高级认证数据
		var doAuth=function(key,authData){
			console.log(key);
			console.log(authData);
			if(key=='saveJuHeMno'){
				//运营商实名认证
				CreditService.saveJuHeMno(authData).then(function(response) {
					if(response.success=="success"){
						$ionicPopup.alert({title:'系统提示',template:response.message}).then(function(res){
							//将该图标点亮
							//$scope.zlMap[key].status=1;
							$scope.cancelCreditOk();
						});
					}else{
						$ionicPopup.alert({title:'系统提示',template:response.message});
					}
		        });
			}else if(key=='saveJuHeBankCredit'){
				//央行征信页面
		        $scope.bankRechargeUrl=$sce.trustAsResourceUrl(userServerAdr+"/app/saveJuHeBankCredit.htm?userId="+
		        userId+"&token="+token+"&dealCode="+authData.dealCode+"&username="+authData.username+
		        "&password="+authData.password+"&middleAuthCode="+authData.middleAuthCode);
				$ionicModal.fromTemplateUrl('templates/credit/authPage.html', {
				    scope: $scope,
				    animation: 'slide-in-up'
				}).then(function(modal) {
				    $scope.modal = modal;
				    $scope.modal.show();
				});
			}else if(key=='saveJuHeRegister'){
				//户籍认证
				CreditService.saveJuHeRegister(authData).then(function(response) {
					if(response.success=="success"){
						$ionicPopup.alert({title:'系统提示',template:response.message}).then(function(res){
							//将该图标点亮
							//$scope.zlMap[key].status=1;
							$scope.cancelCreditOk();
						});
					}else{
						$ionicPopup.alert({title:'系统提示',template:response.message});
					}
		        });
			}else if(key=='saveJuHeZmxy'){
				//芝麻信用
		        $scope.bankRechargeUrl=$sce.trustAsResourceUrl(userServerAdr+"/app/saveJuHeZmxy.htm?userId="+
		        userId+"&token="+token+"&dealCode="+authData.dealCode);
		        console.log(userServerAdr+"/app/saveJuHeZmxy.htm?userId="+
		        userId+"&token="+token+"&dealCode="+authData.dealCode);
				$ionicModal.fromTemplateUrl('templates/credit/authPage.html', {
				    scope: $scope,
				    animation: 'slide-in-up'
				}).then(function(modal) {
				    $scope.modal = modal;
				    $scope.modal.show();
				});
				
				
			}else if(key=='saveJuHeBankCard'){
				//银行卡消费认证
				CreditService.getBankCardInfo(authData).then(function(response) {
					if(response.success=="success"){
						$ionicPopup.alert({title:'系统提示',template:response.message}).then(function(res){
							//将该图标点亮
							//$scope.zlMap[key].status=1;
							$scope.cancelCreditOk();
						});
					}else{
						$ionicPopup.alert({title:'系统提示',template:response.message});
					}
		        });
			}else if(key=='saveJuHeFund'){
				//公积金页面
		        $scope.bankRechargeUrl=$sce.trustAsResourceUrl(userServerAdr+"/app/saveJuHeFund.htm?userId="+
		        userId+"&token="+token+"&dealCode="+authData.dealCode+"&username="+authData.username+
		        "&password="+authData.password+"&area="+authData.area);
				$ionicModal.fromTemplateUrl('templates/credit/authPage.html', {
				    scope: $scope,
				    animation: 'slide-in-up'
				}).then(function(modal) {
				    $scope.modal = modal;
				    $scope.modal.show();
				});
			}else if(key=='saveJuHeJingDong'){
				//京东页面
		        $scope.bankRechargeUrl=$sce.trustAsResourceUrl(userServerAdr+"/app/saveJuHeJingDong.htm?userId="+
		        userId+"&token="+token+"&dealCode="+authData.dealCode+"&loginName="+authData.loginName+
		        "&passwd="+authData.passwd);
				$ionicModal.fromTemplateUrl('templates/credit/authPage.html', {
				    scope: $scope,
				    animation: 'slide-in-up'
				}).then(function(modal) {
				    $scope.modal = modal;
				    $scope.modal.show();
				});
			}else if(key=='saveJuHeTaoBao'){
				//淘宝页面
				$scope.bankRechargeUrl=$sce.trustAsResourceUrl(userServerAdr+"/app/saveJuHeTaoBao.htm?userId="+
		        userId+"&token="+token+"&dealCode="+authData.dealCode+"&loginName="+authData.loginName+
		        "&password="+authData.password);
				$ionicModal.fromTemplateUrl('templates/credit/authPage.html', {
				    scope: $scope,
				    animation: 'slide-in-up'
				}).then(function(modal) {
				    $scope.modal = modal;
				    $scope.modal.show();
				});
			}else if(key=='saveJuHeMarrage'){
				//婚姻
				CreditService.saveJuHeMarrage(authData).then(function(response) {
					if(response.success=="success"){
						$ionicPopup.alert({title:'系统提示',template:response.message}).then(function(res){
							//将该图标点亮
							//$scope.zlMap[key].status=1;
							$scope.cancelCreditOk();
						});
					}else{
						$ionicPopup.alert({title:'系统提示',template:response.message});
					}
		        });
			}else if(key=='saveJuHeSecurity'){
				//社保页面
				$scope.bankRechargeUrl=$sce.trustAsResourceUrl(userServerAdr+"/app/saveJuHeSecurity.htm?userId="+
		        userId+"&token="+token+"&dealCode="+authData.dealCode+"&username="+authData.username+
		        "&password="+authData.password+"&area="+authData.area);
				$ionicModal.fromTemplateUrl('templates/credit/authPage.html', {
				    scope: $scope,
				    animation: 'slide-in-up'
				}).then(function(modal) {
				    $scope.modal = modal;
				    $scope.modal.show();
				});
			}else if(key=='saveJuHeDegree'){
				//学位
				CreditService.saveJuHeDegree(authData).then(function(response) {
					if(response.success=="success"){
						$ionicPopup.alert({title:'系统提示',template:response.message}).then(function(res){
							//将该图标点亮
							//$scope.zlMap[key].status=1;
							$scope.cancelCreditOk();
						});
					}else{
						$ionicPopup.alert({title:'系统提示',template:response.message});
					}
		        });
			}else if(key=='saveJuHeFly'){
				//乘机人
				CreditService.saveJuHeFly(authData).then(function(response) {
					if(response.success=="success"){
						$ionicPopup.alert({title:'系统提示',template:response.message}).then(function(res){
							//将该图标点亮
							//$scope.zlMap[key].status=1;
							$scope.cancelCreditOk();
						});
					}else{
						$ionicPopup.alert({title:'系统提示',template:response.message});
					}
		        });
			}else if(key=='saveJuHeDrive'){
				//又是个学位认证
				CreditService.saveJuHeDrive(authData).then(function(response) {
					if(response.success=="success"){
						$ionicPopup.alert({title:'系统提示',template:response.message}).then(function(res){
							//将该图标点亮
							//$scope.zlMap[key].status=1;
							$scope.cancelCreditOk();
						});
					}else{
						$ionicPopup.alert({title:'系统提示',template:response.message});
					}
		        });
			}else if(key=='saveJuHeProfession'){
				//专业资格认证
				CreditService.saveJuHeProfession(authData).then(function(response) {
					if(response.success=="success"){
						$ionicPopup.alert({title:'系统提示',template:response.message}).then(function(res){
							//将该图标点亮
							//$scope.zlMap[key].status=1;
							$scope.cancelCreditOk();
						});
					}else{
						$ionicPopup.alert({title:'系统提示',template:response.message});
					}
		        });
			}else if(key=='saveJuHeCar'){
				//行车证认证
				CreditService.saveJuHeCar(authData).then(function(response) {
					if(response.success=="success"){
						$ionicPopup.alert({title:'系统提示',template:response.message}).then(function(res){
							//将该图标点亮
							//$scope.zlMap[key].status=1;
							$scope.cancelCreditOk();
						});
					}else{
						$ionicPopup.alert({title:'系统提示',template:response.message});
					}
		        });
			}
		}
		
		
	}
	
})

//信用明细
.controller('CreditDetailCtrl', function($scope,CreditService) {
	
	//查询信用明细
	var page=0;
	$scope.noMore=true;
	$scope.creditDetails=[];
	$scope.loadCreditDetails=function(){
		CreditService.getCreditDetail(page).then(function(response) {
			$scope.$broadcast('scroll.infiniteScrollComplete');
			if(response.data!=null&&response.data!=''){
				if(response.data.length<=0){
					$scope.noMore=false;
				}else{
					for(var i=0;i<response.data.length;i++){
						$scope.creditDetails.push(response.data[i]);
					}
					page=page+1;
				}
			}else{
				$scope.noMore=false;
			}
		});
	}
	
	
})

//信用收益
.controller('IncomeCtrl', function($scope,CreditService,$ionicPopup,$location,$state,$ionicScrollDelegate) {
	
	//收益转余额
	$scope.incomeToBalance=function(){
		CreditService.convertIncomeToBalance().then(function(response) {	
			$ionicPopup.alert({title:'系统提示',template:response.message});
			
			//重新加载数据
			CreditService.getCreditInComes(page).then(function(response) {
				if(response.success=='success'){
					$scope.unAmount=response.data.unAmount;
				}
			});
			
		});
	}
	
	//领取收益
	$scope.receiveInterest=function(interestId){
		CreditService.receiveInterest(interestId).then(function(response) {	
			$ionicPopup.alert({title:'系统提示',template:response.message});
			if(response.success=='success'){
				$scope.creditInComes=[];
				page=0;
				$ionicScrollDelegate.scrollTop();
			}
		});
	}
	
	//查询信用等级信息
	$scope.data={};
	CreditService.getCreditLevel().then(function(response) {
		if(response.success=="success"){
			$scope.data=response.data;
		}
	});
	
	var page=0;
	$scope.noMore=true;
	$scope.creditInComes=[];
	var loadCreditInComes=function(){
		CreditService.getCreditInComes(page).then(function(response) {
			$scope.unAmount=response.data.unAmount;
			$scope.$broadcast('scroll.infiniteScrollComplete');
			if(response.data.interests!=null&&response.data.interests!=''){
				if(response.data.interests.length<=0){
					$scope.noMore=false;
				}else{
					for(var i=0;i<response.data.interests.length;i++){
						var date=new Date();
						var nowDate=date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate();
						var insterestTime=new Date(response.data.interests[i].createTime);
						var insterestDate=insterestTime.getFullYear()+"-"+(insterestTime.getMonth()+1)+"-"+insterestTime.getDate();
						if(nowDate==insterestDate){
							if(response.data.interests[i].status==0){
								//可领
								response.data.interests[i].status=0;
							}else{
								//已领
								response.data.interests[i].status=1;
							}
						}else{
							if(response.data.interests[i].status==0){
								//过期
								response.data.interests[i].status=2;
							}else{
								//已领
								response.data.interests[i].status=1;
							}
						}
						$scope.creditInComes.push(response.data.interests[i]);
					}
					page=page+1;
				}
			}else{
				$scope.noMore=false;
			}
		},function(e){
			$scope.noMore=false;
		});
		
		if(page>10){
			$scope.noMore=false;
		}
	}
	
	$scope.loadCreditInComes=loadCreditInComes;
	
})

//三个认证界面，实名认证，必填类认证，运营商认证
.controller('AuthenticationController',function($scope,$ionicPopup,$timeout,$sce,$ionicModal,CreditService,$window,$state,$ionicHistory){
	//查询认证状态
	CreditService.getCreditExamineStatus().then(function(response) {
		if(response.success=='success'){		
			$scope.examineStatus=response.data;
			//是否实名绑卡、必填类、运营商认证
			if($scope.examineStatus.isCertificate==1 &&$scope.examineStatus.generalInfoStatus==2&&$scope.examineStatus.mnoStatus==1 && $scope.examineStatus.mnoAccountStatus==1){			
				$state.go('tab.addProduce');
			}
		}
	});
	

	
	var myPopup;
	//认证选择
	$scope.operatorNum=function(){
		$state.go('tab.mno',{back:'1'});	
		
	}
	
	var passwordPopup;
	//通道选择执行
	$scope.operator=function(num){
		var userId=null;
        var token=null;
        try{
        	userId=JSON.parse($window.localStorage["user"] || '{}').userId;
        	token=JSON.parse($window.localStorage["user"] || '{}').token;
        }catch(e){

        }
        
        //服务密码，交易密码
        var data={};
        data.userId=userId;
        data.token=token;
        $scope.data=data;
        // 密码输入框
		passwordPopup = $ionicPopup.show({
			template: '<div class="list" style="margin-bottom: 0px;">'+
				'<label class="item item-input">'+
	  				'<span class="input-label">服务密码</span>'+
	  				'<input type="password" placeholder="请输入运营商服务密码" ng-model="data.password">'+
	  			'</label>'+
	  			'<label class="item item-input">'+
	  				'<span class="input-label">交易密码</span>'+
	  				'<input type="password" placeholder="请输入交易密码" ng-model="data.dealCode">'+
	  			'</label>',
			title: '请输入密码',
			scope: $scope,
			buttons: [
				{
					text:'取消'
				},
				{ 
					text: '确定',
					type: 'button-positive',
					onTap: function(e) {
						if(data.password==null||data.password==''){
							e.preventDefault();
							$ionicPopup.alert({title:'系统提示',template:'服务密码不能为空'});
							return ;
						}
						if(data.dealCode==null||data.dealCode==''){
							e.preventDefault();
							$ionicPopup.alert({title:'系统提示',template:'交易密码不能为空'});
							return ;
						}
						//关闭弹出框
						myPopup.close();
						//跳转认证
				        jumpOperator(num,data);
					}
				}
			]
		});
	}
	
	
	
	//跳转到运营商认证
	var jumpOperator=function(num,data){
		if(num==1){
			$scope.url=$sce.trustAsResourceUrl(userServerAdr+'/app/saveApixMnoAccountFirst.htm?userId='
			+data.userId+'&token='+data.token+'&password='+data.password+'&dealCode='+data.dealCode);
			$ionicModal.fromTemplateUrl('templates/zjr/operatorCertification.html', {
			    scope: $scope,
			    animation: 'slide-in-up'
			}).then(function(modal) {
			    $scope.modal = modal;
			    $scope.modal.show();
			});
		}
		if(num==2){
			//通道二
			$scope.url=$sce.trustAsResourceUrl(userServerAdr+'/app/saveJuHeMnoAccount.htm?userId='
			+data.userId+'&token='+data.token+'&password='+data.password+'&dealCode='+data.dealCode);
			$ionicModal.fromTemplateUrl('templates/zjr/operatorCertification.html', {
			    scope: $scope,
			    animation: 'slide-in-up'
			}).then(function(modal) {
			    $scope.modal = modal;
			    $scope.modal.show();
			});
		}
		if(num==3){
			//人工通道
			CreditService.saveSystemMno(data).then(function(response){
				if(response.success=='success'){
					$ionicPopup.alert({title:'系统提示',template:response.message}).then(function(res){
						$state.go('tab.addProduce');
					});
				}else{
					$ionicPopup.alert({title: '系统提示',template: response.message});
				}
			});
		}
		
		//返回到实名认证界面
		$scope.cancel=function(){
			$scope.modal.hide();
			$state.go('tab.addProduce');
			return ;
		}
	}
})
.controller('MnoCtrl',function($scope,$ionicPopup,$timeout,$sce,$ionicModal,CreditService,$window,$state,$ionicHistory,$stateParams){
	//判断用户是否认证
	$scope.isMonFirmName=false;
	$scope.isMonAnalysis=false;
	//查询认证状态
	CreditService.getCreditExamineStatus().then(function(response) {
		console.log(response);
		if(response.success=='success'){
			//运营商数据分析
			if(response.data.mnoAccountStatus==1){
				$scope.isMonAnalysis=true;	
			}
			// 运营商实名认证状态
			if(response.data.mnoStatus==1){
				$scope.isMonFirmName=true;
			}	
			
		}
	});
	
	
	//运营商实名认证
	$scope.monFirmName=function(){
		var userId=null;
        var token=null;
        try{
        	userId=JSON.parse($window.localStorage["user"] || '{}').userId;
        	token=JSON.parse($window.localStorage["user"] || '{}').token;
        }catch(e){

        }	
		//服务密码，交易密码
        var data={};
        data.userId=userId;
        data.token=token;
        $scope.data=data;
        // 密码输入框
		passwordPopup = $ionicPopup.show({
			template: '<div class="list" style="margin-bottom: 0px;">'+
				'<label class="item item-input">'+
	  				'<span class="input-label">服务密码</span>'+
	  				'<input type="password" placeholder="请输入运营商服务密码" ng-model="data.password">'+
	  			'</label>'+
	  			'<label class="item item-input">'+
	  				'<span class="input-label">交易密码</span>'+
	  				'<input type="password" placeholder="请输入交易密码" ng-model="data.dealCode">'+
	  			'</label>',
			title: '请输入密码',
			scope: $scope,
			buttons: [
				{
					text:'取消'
				},
				{ 
					text: '确定',
					type: 'button-positive',
					onTap: function(e) {
						if(data.password==null||data.password==''){
							e.preventDefault();
							$ionicPopup.alert({title:'系统提示',template:'服务密码不能为空'});
							return ;
						}
						if(data.dealCode==null||data.dealCode==''){
							e.preventDefault();
							$ionicPopup.alert({title:'系统提示',template:'交易密码不能为空'});
							return ;
						}
					//查询认证状态
					CreditService.saveJuHeMno(data).then(function(response) {
					$ionicPopup.alert({title:'系统提示',template:response.message}).then(function(res){
						 //查询认证状态
						CreditService.getCreditExamineStatus().then(function(response) {
							console.log(response);
							if(response.success=='success'){
								//运营商数据分析
								if(response.data.mnoAccountStatus==1){
									$scope.isMonAnalysis=true;	
								}
								// 运营商实名认证状态
								if(response.data.mnoStatus==1){
									$scope.isMonFirmName=true;
								}	
								
							}
						});
	
				    });
					});
					}
				}
			]
		});
	}
 var myPopup;	
   //运营商数据分析
	$scope.monAnalysis=function(){
		var userId=null;
        var token=null;
        try{
        	userId=JSON.parse($window.localStorage["user"] || '{}').userId;
        	token=JSON.parse($window.localStorage["user"] || '{}').token;
        }catch(e){

        }	
	    //认证选择
		myPopup = $ionicPopup.show({
			template: '<div class="list">' +
				'<a class="item item-icon-left" style="padding-left:10px;" ng-click="operator(1)">' +
				'<div style="padding-left:0px;float:left;width:50%;">通道一</div><div style="font-size:13px;float:left;">认证费用2元</div>' +
				'</a>' +
				'<a class="item item-icon-left" style="padding-left:10px;" ng-click="operator(2)">' +
				'<div style="padding-left:0px;float:left;width:50%;">通道二</div><div style="font-size:13px;float:left;">认证费用2元</div>' +
				'</a>'+
				'<a class="item item-icon-left" style="padding-left:10px;" ng-click="operator(3)">' +
				'<div style="padding-left:0px;float:left;width:50%;">人工通道</div><div style="font-size:13px;float:left;">认证费用6元</div>' +
				'<div style="font-size:11px;float:left;">处理（48小时）失效，费用自动退回</div>' +
				'</a>'+
				'<div style="background-color:white;padding-left:10px;padding-right:10px;">'+
	  			'<div>获取服务密码方式</div>'+
	  			'<div>移动：编辑短信“502”发送至“10086”，根据短信提示操作</div>'+
	  			'<div>电信：请拨打“10001”按提示进行操作</div>'+
	  			'<div>联通：编辑短信“405”发送至“10010”，根据短信提示操作</div>'+
	  			'</div>'+
			'</div>',
			title: '请选择认证通道',
			scope: $scope,
			cssClass: 'my-custom-popup',
			buttons: [
				{ text: '取消' },
			]
		});
		
	 }
    var passwordPopup;
	//通道选择执行
	$scope.operator=function(num){
		var userId=null;
        var token=null;
        try{
        	userId=JSON.parse($window.localStorage["user"] || '{}').userId;
        	token=JSON.parse($window.localStorage["user"] || '{}').token;
        }catch(e){

        }
        
        //服务密码，交易密码
        var data={};
        data.userId=userId;
        data.token=token;
        $scope.data=data;
        // 密码输入框
		passwordPopup = $ionicPopup.show({
			template: '<div class="list" style="margin-bottom: 0px;">'+
				'<label class="item item-input">'+
	  				'<span class="input-label">服务密码</span>'+
	  				'<input type="password" placeholder="请输入运营商服务密码" ng-model="data.password">'+
	  			'</label>'+
	  			'<label class="item item-input">'+
	  				'<span class="input-label">交易密码</span>'+
	  				'<input type="password" placeholder="请输入交易密码" ng-model="data.dealCode">'+
	  			'</label>',
			title: '请输入密码',
			scope: $scope,
			buttons: [
				{
					text:'取消'
				},
				{ 
					text: '确定',
					type: 'button-positive',
					onTap: function(e) {
						if(data.password==null||data.password==''){
							e.preventDefault();
							$ionicPopup.alert({title:'系统提示',template:'服务密码不能为空'});
							return ;
						}
						if(data.dealCode==null||data.dealCode==''){
							e.preventDefault();
							$ionicPopup.alert({title:'系统提示',template:'交易密码不能为空'});
							return ;
						}
						//关闭弹出框
						myPopup.close();
						//跳转认证
				        jumpOperator(num,data);
					}
				}
			]
		});
	}
	
	//跳转到运营商认证
	var jumpOperator=function(num,data){
		if(num==1){
			$scope.url=$sce.trustAsResourceUrl(userServerAdr+'/app/saveApixMnoAccount.htm?userId='
			+data.userId+'&token='+data.token+'&password='+data.password+'&dealCode='+data.dealCode);
			$ionicModal.fromTemplateUrl('templates/zjr/operatorCertification.html', {
			    scope: $scope,
			    animation: 'slide-in-up'
			}).then(function(modal) {
			    $scope.modal = modal;
			    $scope.modal.show();
			});
		}
		if(num==2){
			//通道二
			$scope.url=$sce.trustAsResourceUrl(userServerAdr+'/app/saveJuHeMnoAccount.htm?userId='
			+data.userId+'&token='+data.token+'&password='+data.password+'&dealCode='+data.dealCode);
			$ionicModal.fromTemplateUrl('templates/zjr/operatorCertification.html', {
			    scope: $scope,
			    animation: 'slide-in-up'
			}).then(function(modal) {
			    $scope.modal = modal;
			    $scope.modal.show();
			});
		}
		if(num==3){
			//人工通道
			CreditService.saveSystemMno(data).then(function(response){
				if(response.success=='success'){
					$ionicPopup.alert({title:'系统提示',template:response.message}).then(function(res){
						$state.go('tab.mno');
					});
				}else{
					$ionicPopup.alert({title: '系统提示',template: response.message});
				}
			});
		}
		
		//返回到实名认证界面
		$scope.cancel=function(){
			$scope.modal.hide();
			$state.go('tab.mno');
			return ;
		}
	}
	if($stateParams.back==1){
		$scope.back=true;
	}
	$scope.go= function(){
		$state.go('tab.credit');
	}

})
.controller('creditHelpCtrl',function($scope,$cordovaClipboard,$ionicPopup){
	//复制天下无赖诚信联盟
	$scope.copytxwlcxlm=function(){
		try{
			$cordovaClipboard.copy("天下无赖诚信联盟").then(function () {
				
		      	$ionicPopup.alert({title:'系统提示',template:'成功复制'});
		    }, function () {
		      	$ionicPopup.alert({title:'系统提示',template:'复制失败'});
		    });
		}catch(e){
			$ionicPopup.alert({title:'系统提示',template:'复制失败'});
		}
	}
	
})

;